package com.iteaj.demo.server;

import com.iteaj.demo.server.protocol.ClientRequestPlatformDemoProtocol;
import com.iteaj.network.AbstractProtocol;
import com.iteaj.network.Message;
import com.iteaj.network.ProtocolException;
import com.iteaj.network.config.DeviceProperties;
import com.iteaj.network.server.component.SimpleChannelDecoderComponentAdapter;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import org.springframework.stereotype.Component;

@Component
public class ServerDemoServerComponent extends SimpleChannelDecoderComponentAdapter<ServerDemoMessage> {

    public ServerDemoServerComponent() {
        super(new DeviceProperties(8888));
    }

    @Override
    public String name() {
        return "服务端Demo";
    }

    @Override
    public String desc() {
        return "服务端测试服务";
    }

    @Override
    public ServerDemoMessage decode(ChannelHandlerContext ctx, ByteBuf in) throws Exception {
        final int readableBytes = in.readableBytes();
        if(readableBytes > 0) {
            final byte[] bytes = new byte[readableBytes];
            in.readBytes(bytes);

            return new ServerDemoMessage(bytes);
        }

        return null;
    }

    @Override
    public AbstractProtocol getProtocol(ServerDemoMessage message) {
        final Message.MessageHead head = message.getHead();
        ServerProtocolType type = head.getTradeType();
        if(type == ServerProtocolType.PlatformRequest) {
            final AbstractProtocol requestProtocol = remove(head.getMessageId());
            if(requestProtocol == null) {
                throw new ProtocolException("请求协议可能已经超时或者移除");
            }

            return requestProtocol.setResponseMessage(message)
                    .buildResponseMessage();
        } else if(type == ServerProtocolType.ClientRequest) {
            return new ClientRequestPlatformDemoProtocol(message).buildRequestMessage();
        } else {
            throw new ProtocolException("错误的协议类型[" +type+ "]");
        }
    }
}
